import {LeftMenuInter} from '@/mock/menu'
import router from '@/router';
import { RouteRecordRaw } from 'vue-router'


// 根据keyIndex获取父级全部的keyIndex数组
export const getParentKeyIndexs = (keyIndex: string) => {
    const keyList = keyIndex.split('-');
    const resKeyList = [] as string[];
    keyList.reduce((totalKeyIndex: string,currentKeyIndex: string)=>{
      const targetKeyIndex = currentKeyIndex?(totalKeyIndex?totalKeyIndex+'-'+currentKeyIndex:currentKeyIndex):totalKeyIndex;
      resKeyList.push(targetKeyIndex)
      return targetKeyIndex
    },'')
    return resKeyList
}


// 根据menu的keyIndex获取对应的请求url
export const getRequestUrlByKeyIndex = (keyIndex: string,menuList: Array<LeftMenuInter>|any) => {
  let url = ''
  for(let i=0;i<menuList.length;i++){
      if(menuList[i].keyIndex===keyIndex){
        url = menuList[i].url
        break;
      }
      else{
          if(menuList[i].children){
              url =  getRequestUrlByKeyIndex(keyIndex,menuList[i].children)
              if(url){
                  break;
              }
          }
      }
  }
  return url;
}

// 根据menu的请求url获取对应的父级keyIndex数组和当前的keyIndex
export const getKeyIndexInfoByRequestUrl = (url: string,menuList: Array<LeftMenuInter>|any) => {
    const keyIndexInfo = {
        openedKeys : [] as string[],  // 展开的keys
        selectedKeys: [] as string[] // 选中的keys
    }
    for(let i=0;i<menuList.length;i++){
        if(menuList[i].url===url||url.startsWith(menuList[i].url)){
            keyIndexInfo.selectedKeys = [menuList[i].keyIndex||'']
            keyIndexInfo.openedKeys = getParentKeyIndexs(menuList[i].keyIndex||'')
            return keyIndexInfo;
        }else{
            if(menuList[i].children){
                const res: any = getKeyIndexInfoByRequestUrl(url,menuList[i].children)
                if(res?.selectedKeys.length&&res?.openedKeys.length){
                    return res;
                }
            }
        }
    }
    return keyIndexInfo
}


//判断path在不在路由数组里
export const checkHavePathInRoutes = (path: string,routes: RouteRecordRaw[] | any) => {
    for(let i=0;i<routes.length;i++){
        if(routes[i].path===path||routes[i].path===path+'/:page*') return true
        else if(path.startsWith(routes[i].path.replace('/:page*',''))) return true
        else{
            if(routes[i].children){
                const checkResult = checkHavePathInRoutes(path,routes[i].children)
                if(checkResult) return true;
            }
        }
    }
    return false
}